package me.frank.tman.ui.trade;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

import me.frank.tman.R;
import me.frank.tman.model.StockExchangeModel;
import me.frank.tman.model.StockModel;
import me.frank.tman.presenter.StockPresenter;

public class TradeFragment extends Fragment {

    private static final String TAG = TradeFragment.class.getSimpleName();

    private ViewPager mViewPager;
    private TabLayout mTab;

    private StockPresenter mPresenter = StockPresenter.get();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_trade, container, false);

        Log.d(TAG, "onCreateView");

        mViewPager = root.findViewById(R.id.tradeViewPager);
        mTab = root.findViewById(R.id.tradeTabLayout);

        List<Fragment> fragments = new ArrayList<>();
        ExchangeFragment buyFragment = new BuyFragment();
        ExchangeFragment sellFragment = new SellFragment();
        SetupFragment setupFragment = new SetupFragment();


        Bundle bundle = getArguments();
        String exchangeType = null;
        if (bundle != null) {
            String stockCode = bundle.getString("stock_code");
            exchangeType = bundle.getString("exchange_type");
            StockExchangeModel model = mPresenter.getLatestExchangRecord(stockCode);

            if (model != null) {
                StockModel stockModel = new StockModel(model.code, model.name);
                buyFragment.setStockModel(stockModel);
                sellFragment.setStockModel(stockModel);
                setupFragment.setStockModel(stockModel);
            }
        }

        fragments.add(buyFragment);
        fragments.add(sellFragment);
        fragments.add(setupFragment);

        String[] titles = {getString(R.string.tab_buy), getString(R.string.tab_sell), getString(R.string.tab_seteup)};

        TradeViewPagerAdapter adapter = new TradeViewPagerAdapter(getChildFragmentManager(), fragments, titles);
        mViewPager.setAdapter(adapter);
        mTab.setupWithViewPager(mViewPager);

        if (StockExchangeModel.SELL.equals(exchangeType)) {
            mViewPager.setCurrentItem(1);
        } else {
            mViewPager.setCurrentItem(0);
        }

        return root;
    }
}